"""
Copyright (c) 2017 Dependable Systems Laboratory, EPFL

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""


import glob
import json
import logging
import os
import re


logger = logging.getLogger('coverage')

TB_COVERAGE_FILE_STATE_REGEX = re.compile(r'tbcoverage-(?P<state>\d+)\.json$')


def get_tb_files(results_dir):
    """
    Gets a list of translation block coverage files generated by S2E's
    TranslationBlockCoverage plugin.

    Args:
        results_dir: Path to an ``s2e-out-*`` directory in an analysis project.

    Returns:
        A list of translation block coverage files.
    """
    # Include both multi-node and single node results
    tb_coverage_files = glob.glob(os.path.join(results_dir, '*', 'tbcoverage-*.json')) + \
                        glob.glob(os.path.join(results_dir, 'tbcoverage-*.json'))
    if not tb_coverage_files:
        logger.warning('No translation block coverage files found in %s. '
                       'Did you enable the ``TranslationBlockCoverage`` '
                       'plugin in s2e-config.lua?', results_dir)

    return tb_coverage_files


def get_tb_state(tb_coverage_file):
    """
    Extract the state ID from the given TB coverage file path. Return ``None``
    if no match is found.
    """
    match = TB_COVERAGE_FILE_STATE_REGEX.search(tb_coverage_file)
    if match:
        return int(match.group('state'))

    return None


def _touint64(num):
    """
    This is required to convert signed json integers to unsigned.
    """
    return num & 0xffffffffffffffff


def _tb_to_uint64(tb):
    start_addr = _touint64(tb[0])
    end_addr = _touint64(tb[1])
    size = tb[2]
    return start_addr, end_addr, size


def aggregate_tb_files_per_state(tb_files):
    """
    Aggregate translation block coverage information from all files and
    put them in a single dict that maps module paths to their translation block
    coverage.
    """
    ret = {}
    for f in tb_files:
        with open(f, 'r', encoding='utf-8') as fp:
            try:
                data = json.load(fp)
            except Exception:
                logger.warning('Failed to parse translation block JSON file %s', f)
                continue

            if not data:
                logger.warning('Translation block JSON file %s is empty', f)
                continue

            state_id = get_tb_state(f)

            for module_path, coverage in data.items():
                states = {}
                if module_path not in ret:
                    ret[module_path] = states
                else:
                    states = ret[module_path]

                tbs = set()
                if state_id not in states:
                    states[state_id] = tbs
                else:
                    tbs = states[state_id]

                for tb in coverage:
                    tbs.add(_tb_to_uint64(tb))
    return ret


def aggregate_tb_files(tb_files):
    ret = {}
    tbs = aggregate_tb_files_per_state(tb_files)
    for module_path, states in tbs.items():
        tbs = set()
        ret[module_path] = tbs
        for coverage in states.values():
            for tb in coverage:
                tbs.add(_tb_to_uint64(tb))
    return ret
